package publisher

import (
	"fmt"
	"time"

	MQTT "github.com/eclipse/paho.mqtt.golang"
)

const (
	serverURI    = "tcp://mq.heatwatch.cn:1983"   // MQTT 服务器地址
	topic        = "tmr/ryjt/kptmqtt1/ryjt1/pycx" // 主题名称
	qos          = 1                              // QoS 等级
	clientID     = "ryjt1"                        // 客户端 ID
	cleanSession = true                           // 清除会话状态
	password     = "123"                          // 密码
	userName     = "kptmqtt1"                     // 用户名
)

func NewPublisher() {
	opts := MQTT.NewClientOptions().
		AddBroker(serverURI).
		SetClientID(clientID).
		SetCleanSession(cleanSession).
		SetPassword(password).
		SetUsername(userName)

	// 创建 MQTT 客户端
	client := MQTT.NewClient(opts)

	// 连接到 MQTT 服务器
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	fmt.Println("Connected to MQTT broker:", serverURI)
	fmt.Println("Connected to MQTT top:", topic)

	// 模拟发送消息
	for i := 0; i < 5; i++ {
		message := fmt.Sprintf("Message %d", i+1)
		publishMessage(client, topic, message)
		time.Sleep(1 * time.Second) // 每秒发送一条消息
	}

	// 断开与 MQTT 服务器的连接
	client.Disconnect(250)
	fmt.Println("Disconnected from MQTT broker")
}

// 发布消息函数
func publishMessage(client MQTT.Client, topic string, payload string) {
	token := client.Publish(topic, qos, false, payload)
	token.Wait()
	fmt.Printf("Published message: %s\n", payload)
}
